const { GoogleSpreadsheet } = require("google-spreadsheet");

require("dotenv").config();
const {
  GOOGLE_SPREADSHEET_ID,
  GOOGLE_SERVICE_ACCOUNT_EMAIL,
  GOOGLE_PRIVATE_KEY,
} = process.env;

const doc = new GoogleSpreadsheet(GOOGLE_SPREADSHEET_ID);
doc.useServiceAccountAuth({
  client_email: GOOGLE_SERVICE_ACCOUNT_EMAIL,
  private_key: GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n"),
});

const logger = async (name, id) => {
  await doc.loadInfo();
  const sheet = doc.sheetsByIndex[6];
  await sheet.loadCells("A1:B100");
  sheet.addRow([name, id]);

};
const loggerMidlware = async (ctx, next) => {
  const loadingMessage = await ctx.reply("Загрузка данных...");
  const user = ctx.from.id;
  await doc.loadInfo();
  const sheet = doc.sheetsByIndex[6];
  await sheet.loadCells("A1:ZZ50");
  const rows = await sheet.getRows();
  const searchId = rows.find((row) => {
    return row.id === String(user);
  });
  if (!searchId) {
  ctx.deleteMessage(loadingMessage.message_id);
  ctx.reply("Зарегистрируйся, нажми 👉 /reg");
} else {
  ctx.deleteMessage(loadingMessage.message_id);
  next();
}

};
const searchOnboarding = async (ctx) => {
  try {
    const buttons = ctx.callbackQuery.message.reply_markup.inline_keyboard;
    const user = ctx.from.id;
    await doc.loadInfo();
    const sheet = doc.sheetsByIndex[6];
    await sheet.loadCells("A1:ZZ50");
    const rows = await sheet.getRows();
    const headerValues = sheet.headerValues;
    const row = rows.find((row) => {
      return row.id === String(user);
    });

    let cellName = "";
    let delay = 100;

    for (let buttonRow of buttons) {
      for (let button of buttonRow) {
        setTimeout(async () => {
          if (button.text.includes("✅")) {
            if (button.callback_data.includes("(Night)")) {
              cellName = button.callback_data.replace(" (Night)", "");
              console.log(cellName);
              const rowNumber = row._rowNumber - 1;
              const columnIndex = headerValues.indexOf(cellName);
              console.log(columnIndex)
              const cell = sheet.getCell(rowNumber, columnIndex);
              cell.value = "Ночь";
              await sheet.saveUpdatedCells();

              console.log("yes ночь");
            } else {
              cellName = button.callback_data.replace(" (Day)", "");
              console.log(cellName);
              const rowNumber = row._rowNumber - 1;
              const columnIndex = headerValues.indexOf(cellName);
              console.log(columnIndex)
              const cell = sheet.getCell(rowNumber, columnIndex);
              cell.value = "День";
              await sheet.saveUpdatedCells();
              console.log("yes день");
            }
          } else if (
            button.callback_data.replace(" (Night)", "") !== cellName &&
            button.callback_data.replace(" (Day)") !== cellName &&
            !button.callback_data.includes("Отправить")
          ) {
            if (button.callback_data.includes("(Day")) {
              cellName = button.callback_data.replace(" (Day)", "");
              console.log(cellName);
              const rowNumber = row._rowNumber - 1;
              const columnIndex = headerValues.indexOf(cellName);
              console.log(columnIndex)
              const cell = sheet.getCell(rowNumber, columnIndex);
              cell.value = "";
              await sheet.saveUpdatedCells();
              console.log("none Day");
            } else {
              cellName = button.callback_data.replace(" (Day)", "");
              console.log(cellName);
              const rowNumber = row._rowNumber - 1;
              const columnIndex = headerValues.indexOf(cellName);
              console.log(columnIndex)
              const cell = sheet.getCell(rowNumber, columnIndex);
              cell.value = "";
              await sheet.saveUpdatedCells();
              console.log("none Night");
            }
          }
        }, delay);
        delay += 500; // Increase the delay duration by 1 second for the next iteration
      }
    }
  } catch (error) {
    ctx.reply("Ошибка, записи данных в таблицу. Попробуй еще раз");
    console.error(error);
  }
  // Handle the error here
  // } finally {ctx.reply(`Дата выхода на смену:\n${messageDate.join("\n")}`);}
};

module.exports = { searchOnboarding, loggerMidlware, logger };
